package com.zhongli.devplatform.service.impl.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongli.devplatform.bean.PageVO;
import com.zhongli.devplatform.dto.sys.DictionaryItemDTO;
import com.zhongli.devplatform.mapper.sys.DictionaryItemMapper;
import com.zhongli.devplatform.po.sys.DictionaryItemPO;
import com.zhongli.devplatform.query.sys.DictionaryItemQuery;
import com.zhongli.devplatform.service.imp.sys.IDictionaryItemService;
import com.zhongli.devplatform.utils.BeanCopierUtil;
import com.zhongli.devplatform.vo.sys.DictionaryItemVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DictionaryItemServiceImpl implements IDictionaryItemService {

    @Autowired
    private DictionaryItemMapper dictionaryItemMapper;


    @Override
    public PageVO<DictionaryItemVO> listPage(DictionaryItemQuery query) {
        QueryWrapper queryWrapper = new QueryWrapper<DictionaryItemPO>();

        if (!StringUtils.isBlank(query.getName())) {
            queryWrapper.like("name", query.getName());
            queryWrapper.or(true).eq("value", query.getName());
        }
        if (query.getDictionaryDirectoryId() != null) {
            queryWrapper.eq("dictionary_directory_id", query.getDictionaryDirectoryId());
        }
        queryWrapper.orderByDesc("order_num");

        Page page = dictionaryItemMapper.selectPage(query, queryWrapper);
        PageVO newPage = PageVO.convert(page);
        newPage.setRecords(BeanCopierUtil.copy(page.getRecords(), DictionaryItemVO.class));
        return newPage;
    }

    @Override
    public void save(DictionaryItemDTO dictionaryItemDTO) {
        DictionaryItemPO dictionaryItemPO = BeanCopierUtil.copy(dictionaryItemDTO, DictionaryItemPO.class);
        if (dictionaryItemPO.getId() == null) {
            dictionaryItemMapper.insert(dictionaryItemPO);
        } else {
            dictionaryItemMapper.updateById(dictionaryItemPO);
        }
    }

    @Override
    public void delete(List<Long> ids) {
        dictionaryItemMapper.deleteBatchIds(ids);
    }

    @Override
    public Boolean isExist(DictionaryItemQuery query) {

        QueryWrapper queryWrapper = new QueryWrapper<DictionaryItemPO>();
        if (!StringUtils.isBlank(query.getValue())) {
            queryWrapper.eq("value", query.getValue());
        }
        if (!StringUtils.isBlank(query.getName())) {
            queryWrapper.eq("name", query.getName());
        }
        queryWrapper.eq("dictionary_directory_id", query.getDictionaryDirectoryId());
        if (query.getId() != null) {
            queryWrapper.ne("id", query.getId());
        }

        return dictionaryItemMapper.selectCount(queryWrapper) > 0;
    }

}
